<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 卡片布局 -->
      <el-card>
        <!-- 标签页切换 -->
        <el-tabs>
          <!-- 标签页1：角色管理 -->
          <el-tab-pane label="角色管理">
            <!-- Layout布局(row和col组合)：新增角色按钮 -->
            <el-row style="height: 60px">
              <el-col :offset="22">
                <el-button
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="showDialog = true"
                >新增角色</el-button>
              </el-col>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" stripe border="">
              <el-table-column type="index" label="序号" width="120">
                <template slot-scope="scope">
                  {{ (page.page-1)*page.pagesize+scope.$index+1 }}
                </template>
              </el-table-column>
              <!-- <el-table-column type="index" label="序号" width="120" /> -->
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="assignPermission(scope.row.id)"
                  >分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                layout="sizes,total, prev, pager, next, jumper"
                :total="total"
                :page-size="page.pagesize"
                :page-sizes="[2, 5, 10, 50]"
                background
                @current-change="currentChange"
                @size-change="sizeChange"
              />
            </el-row>
          </el-tab-pane>
          <!-- 标签页2：公司信息 -->
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="formData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="formData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="formData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 弹窗：新增角色 -->
      <el-dialog :title="dialogTitle" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 弹窗：分配权限 -->
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!--
          data:树形组件数据对象
          props:指定组件渲染时使用的字段名
          check-strictly:为true则严格选择，忽略父子节点之间的关联
         -->
        <el-tree
          ref="permTree"
          :data="permData"
          :props="{label:'name'}"
          :show-checkbox="true"
          :check-strictly="true"
          :default-checked-keys="selectCheck"
          node-key="id"
          default-expand-all
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCompanyInfo, getRoleList, deleteRole, updateRole, getRoleDetail, addRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  data() {
    return {
      formData: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      list: [],
      total: 0,
      page: {
        page: 1,
        pagesize: 2
      },
      // 编辑弹窗使用的数据
      showDialog: false,
      // 专门接收新增或者编辑的编辑的表单数据
      roleForm: {},
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '名称长度在2-20之间', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述名称不能为空', trigger: 'blur' },
          { min: 5, max: 200, message: '名称长度在5-200之间', trigger: 'blur' }
        ]
      },
      showPermDialog: false, // 控制分配权限弹层的显示后者隐藏
      defaultProps: {
        label: 'name'
      },
      permData: [], // 专门用来接收权限数据 树形数据
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      roleId: null // 用来记录分配角色的id
    }
  },
  computed: {
    ...mapGetters(['companyId']),
    dialogTitle() {
      return this.roleForm.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    // 获得公司信息
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
    },
    // 获取角色列表
    async getRoleList() {
      // console.log(this.page)
      const { rows, total } = await getRoleList(this.page)
      // console.log(rows)
      this.list = rows
      this.total = total
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getRoleList()
    },
    sizeChange(newSize) {
      this.page.pagesize = newSize
      this.getRoleList()
    },
    async deleteRole(id) {
      try {
        // 二次确认
        await this.$confirm('确认删除该角色？')
        await deleteRole(id)
        await this.getRoleList()
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      // 获取旧数据
      this.roleForm = await getRoleDetail(id)
      // 弹出弹窗
      this.showDialog = true
    },
    async btnOK() {
      // 等用户输入新数据,按下确认按钮
      // 校验数据
      await this.$refs.roleForm.validate()
      // 发请求  区分编辑还是新增
      if (this.roleForm.id) {
        await updateRole(this.roleForm)
      } else {
        await addRole(this.roleForm)
      }
      // 重新加载、关闭弹窗、提示
      await this.getRoleList()
      this.showDialog = false
      this.$message.success('操作成功')
    },
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      // 移除校验
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 权限分配
    async assignPermission(id) {
      const res = await getPermissionList()
      // console.log(res)
      this.permData = transListToTreeData(res, '0')
      // 回显权限
      const { permIds } = await getRoleDetail(id) // permIds是当前角色所拥有的权限点数据
      this.selectCheck = permIds // 将当前角色所拥有的权限id赋值
      this.roleId = id
      this.showPermDialog = true
    },
    btnPermCancel() {
      this.selectCheck = []
      this.showPermDialog = false
    },
    async btnPermOK() {
      // 权限分配请求
      const newSelect = this.$refs.permTree.getCheckedKeys()
      const data = { permIds: newSelect, id: this.roleId }
      await assignPerm(data)
      this.$message.success('操作成功')
      this.showPermDialog = false
    }
  }
}
</script>

<style>
</style>
